jQuery(function(){
	////计算费用
	/*jQuery('#price').blur(function(){
		var price=jQuery("#price").val();
		var amount=jQuery("#amount").val();
		if(!isNaN(Number(price)) && !isNaN(Number(amount))){
			var total=price*amount;
			jQuery("#totalPrice").val(total)
		}
	})*/
	/*jQuery('#amount').blur(function(){
		var price=jQuery("#price").val();
		var amount=jQuery("#amount").val();
		if(!isNaN(Number(price)) && !isNaN(Number(amount))){
			var total=price*amount;
			jQuery("#totalPrice").val(total)
		}
	})*/
	
	//引入客户信息弹窗	 
	 jQuery('#queryCustomer').on("click",function(){
		 showCustomer();//显示客户信息
	 });
	//引入客户信息	 
	 jQuery('#pull-customer-in').on("click",function(){
		 var selects=getSelect("#query-customer-table",1);
	   	   if(selects.length>1){
	   		  message("只能引入一条客户");
	   	   }
	   	   else if(selects.length==0){
	   		   message("没有选中客户");
	   	   }
	   	   else if(selects.length==1){
	   		    jQuery("#orderUnit").val(selects[0].customerName);
	   		    jQuery("#customerCode").val(selects[0].customerCode);
		   		jQuery("#creditLevel").val(selects[0].creditLevel);
		   		jQuery("#customer").val(selects[0].id);
		   		jQuery("#address").val(selects[0].address);
		   		jQuery("#superiorArea").val(selects[0].saleArea.superiorArea);
		   		jQuery("#saleArea").val(selects[0].saleArea.id);
		   		jQuery("#query-Customer-Modal").modal('hide');
	   	   }
	 });
	 /////////客户弹窗显示客户信息和查询
	 var serverData1 = {};
	    serverData1.key="";
	    var serverTable1;
	    jQuery(document).ready(function () {
	        serverTable1 = jQuery('#customerTable').DataTable({
	            "serverSide": true,
	            "ordering": false,
	            "ajax": {
	                "dataType": "json",
	                "type": "get",
	                "cache": false,
	                "url":window.rootPath+ '/ui/customer/getpage',
	                "data": function (d) {
	                    return $.extend({}, d, serverData1);
	                }
	            },
	            "iDisplayLength": 5,
	            columns: [
	                {
	                data: null
	                },
	                {
	                	data: 'customerName'
	                },
	                {
	                    data: 'saleArea.areaName'
	                },
	                {
	                    data: 'business'
	                },
	                {
	                    data: 'superior'
	                },
	                {
	                	data: null,
	                    defaultContent: "",
	                    render: function (data, type, full, meta) {
	                        var operate ='<input type="checkbox" class="checkCustomer">';
	                        return operate;
	                    }
	                    
	                } 
	              ],
	            "drawCallback": function (oSettings) {
	                var k = 0;
	                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

	                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
	                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
	                    k++;
	                }

	                serverTable1.off('click', 'tr');
	                serverTable1.on('click', 'tr', function (event) {
	                    event = event || window.event;
	                    var target = event.target || event.scrElement;
	                    var data = serverTable1.row(this).data();
	                    return;
	                });
	            }
	        });
	    	});
	    //搜索
		jQuery('.searchBtn').on('click', function() {
			serverData1.key = jQuery('#keyword').val();
			serverTable1.draw();
		})
		// 撤销查询
		jQuery('.resetBtn').on("click", function() {
			jQuery('#keyword').val('');
			serverData1.key = '';
			serverTable1.draw();
		});

	
	
    //////////////////////////客户来访信息///////////////////////////////////////////////
	function saveVisit(isreturn){
		var id = jQuery("#visitId").val();
		var visitcreateTime=jQuery("#visitcreateTime").val();
		var createTime=new Date(visitcreateTime).getTime() ;
		var customerId = jQuery('#customer').val();
		var project = jQuery('#project').val();
		var development=jQuery('#development').val();
		var visitingDate = jQuery('#visitingDate').val();
		var contractAmount= jQuery('#contractAmount').val();
		var chance=jQuery('#chance').val();
		var operator = jQuery('#operator').val();
		var prove = jQuery("#prove").val();
		var areaId = jQuery("#saleArea").val();
		var costAtrr = jQuery("#costAtrr").val();
		var memo = jQuery("#memo").val();
		var url = window.rootPath + "/ui/customerVisiting/saveCustomerVisit";
		// 判断是编辑还是新增
		if (id == "") {
			var d = {
				"customer":{
					"id":customerId
				},
				"project" : project,
				"development" : development,
				"chance":chance,
				"operator" : operator,
				"visitingDate" : visitingDate,
				"contractAmount":contractAmount,
				"prove" : prove,
				"saleArea": {
  	                "id": areaId
  	            },
				"costAtrr" : costAtrr,
				"memo" : memo
			}
		}else{
			var d = {
					"id" : id,
					"createTime":createTime,
					"customer":{
						"id":customerId
					},
					"project" : project,
					"development" : development,
					"chance":chance,
					"operator" : operator,
					"visitingDate" : visitingDate,
					"contractAmount":contractAmount,
					"prove" : prove,
					"saleArea": {
	  	                "id": areaId
	  	            },
					"costAtrr" : costAtrr,
					"memo" : memo
				}
		}
		jQuery(".btn").attr("disabled", true);
		jQuery.ajax({
            type: 'post',
            url:  encodeURI(url),
            data: JSON.stringify(d),
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            success: function (data) {
            	jQuery(".btn").attr("disabled", false);
            	if(isreturn==1){
            		window.location = window.rootPath+"/ui/customerVisiting";
            	}
            	else if(isreturn==2){
            		var visitId=data.visitId;
            		saveVisitPerson(visitId);
            		var time=moment(data.createTime).format("YYYY-MM-DD HH:mm:ss");
            		jQuery("#visitcreateTime").val(time);
            	}
            	else if(isreturn==3){
            		var visitId=data.visitId;
            		saveVisitCost(visitId);
            		var time=moment(data.createTime).format("YYYY-MM-DD HH:mm:ss");
            		jQuery("#visitcreateTime").val(time);
            	}
            }
        });		
	}
	// 保存客户来访信息
	jQuery('.saveBtn').on('click', function() {
		if (jQuery("#customerVisit") && !jQuery("#customerVisit").Validform({
			tiptype : 3,
			showAllError : true
		}).check(false)) {
			return;
		};	
		saveVisit(1);	
	});	
//////////////////////////////客户来访人员/////////////////////////////////
////获得客户来访人员 服务器分页
	 var PersonData = {};
	 var visitId=jQuery('#visitId').val();
	 PersonData.visitId=visitId;
	 var personTable;
	    jQuery(document).ready(function () {
	    	personTable = jQuery('#personTable').DataTable({
	            "serverSide": true,
	            "iDisplayLength":5,
	            "ordering": false,
	            "ajax": {
	                "dataType": "json",
	                "type": "get",
	                "cache": false,
	                "url":window.rootPath+ '/ui/customerVisiting/getVisitPerson',
	                "data": function (d) {
	                    return $.extend({}, d, PersonData);
	                }
	            },
	            columns: [
	                {
	                    data: null,
	                    defaultContent: ""//排序
	                },
	                {
	                    data: null,
	                    defaultContent: "",
	                    render: function (data, type, full, meta) {
	    	            	var id=data.id
	    	            	var operate ='<input type="checkbox" class="checkchild1">';
	    	            	return operate;
	    	            }  
	                },
	                {
	                    data: 'name'
	                },
	                {
	                    data: 'department'
	                },
	                {
	                    data: 'position'
	                },	             
	                {
	                    data: 'contractType'
	                },
	                {
	                    data: 'personNum'
	                }
	                ],
	            "drawCallback": function (oSettings) {
	                var k = 0;
	                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
	                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
	                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
	                    k++;
	                }
	            }
	        });
	    	 
	    });
	    ////编辑来访人员
	    jQuery('.editPersonBtn').on('click',function(){
	       var selects=getSelect("#personTable",1);
	 	   if(selects.length>1){
	 		   $.springLemonDialog({
	 		         content: '只能编辑一条记录',// 确认文本
	 		         clickButton: function (sender, modal, index) {// 按钮事件处理
	 		             $(this).closeDialog(modal);
	 		         }
	 		   }); 
	 	   }
	 	   else if(selects.length==0){
	 		   $.springLemonDialog({
	 		         content: '请选择要编辑的记录',// 确认文本
	 		         clickButton: function (sender, modal, index) {// 按钮事件处理
	 		             $(this).closeDialog(modal);
	 		         }
	 		   }); 
	 	   }else if(selects.length==1){
	 		jQuery("#personId").val(selects[0].id);
          	jQuery('#personcreatetime').val(selects[0].createTime);
          	jQuery("#name").val(selects[0].name);
    		jQuery("#department").val(selects[0].department);
    		jQuery('#position').val(selects[0].position);
    		jQuery('#contractType').val(selects[0].contractType);
    		jQuery('#personNum').val(selects[0].personNum);
    		jQuery('#visitingPersonModal').modal('show');
	 	   }	
	    })
	    ///////删除来访人员
	    jQuery('.deletePersonBtn').on('click', function () {
		   var selects=getSelect("#personTable",1);
		   var url=window.rootPath+"/ui/customerVisiting/delVisitPerson";
		   delSelect(selects,url,personTable) 
		});
	    
	    ///////列表中的全选
	    $("#checkAll1").click(function(){
	    	var check = $(this).prop("checked");
	        $(".checkchild1").prop("checked", check);
		});
	   
//////////////////保存来访人员//////////
		jQuery('.savePersonBtn').on('click',function(){
			if (jQuery("#visitingPersonForm") && !jQuery("#visitingPersonForm").Validform({
				tiptype : 3,
				showAllError : true
			}).check(false)) {
				return;
			};
			saveVisit(2);	
		})
	function saveVisitPerson(visitId){
		var id=jQuery("#personId").val();
		var personcreatetime=jQuery("#personcreatetime").val();
		var name=jQuery("#name").val();
		var department=jQuery("#department").val();
		var position=jQuery('#position').val();
		var contractType=jQuery('#contractType').val();
		var personNum=jQuery('#personNum').val();
		var url1=window.rootPath+"/ui/customerVisiting/saveVisitPerson";
		var d;
		if(id==''){
	      	  d = {
	      			"name": name,
	   	            "contractType": contractType,
	   	            "department": department,
	   	            "position": position,
	   	            "personNum": personNum,
	   	            "customerVisiting": {
	   	                "id": visitId
	   	            } 
	   	        };
	      	  	jQuery.ajax({
		          type: 'post',
		          url: encodeURI(url1),
		          data: JSON.stringify(d),
		          dataType: 'json',
		          contentType: 'application/json;charset=utf-8',
		          success: function (data) {
		        		jQuery('#visitingPersonModal').modal('hide');
		        		PersonData.visitId=visitId;
		        		jQuery('#visitId').val(visitId);
		        		personTable.draw();
		          }
	      	  	});
	      }else{
	      	d = {
	   	            "id":id,
	   	            "createTime":personcreatetime,
	   	            "name": name,
	   	            "contractType": contractType,
	   	            "department": department,
	   	            "position": position,
	   	            "personNum": personNum,
	   	            "customerVisiting": {
	   	                "id": visitId
	   	            } 
	   	        };
	      	jQuery(".btn").attr("disabled", true);
	      	jQuery.ajax({
		          type: 'post',
		          url:  encodeURI(url1),
		          data: JSON.stringify(d),
		          dataType: 'json',
		          contentType: 'application/json;charset=utf-8',
		          success: function (data) {
		        	jQuery(".btn").attr("disabled", false);
		          	jQuery('#visitingPersonModal').modal('hide');
		          	jQuery('#visitId').val(visitId);
		          	personTable.draw(false);
		          }
		      });
	      }
	}
	//新增来访人员
	jQuery(".addPersonBtn").on("click",function(){
		var id=jQuery('#visitId').val();
		if (jQuery("#customerVisit") && !jQuery("#customerVisit").Validform({
			tiptype : 3,
			showAllError : true
		}).check(false)) {
			return;
		};
		jQuery("#personId").val('');
		jQuery("#name").val('');
		jQuery("#department").val('');
		jQuery('#position').val('');
		jQuery('#contractType').val('');
		jQuery('#personNum').val('');
		jQuery("#visitingPersonModal").modal('show');	
    });
//////////////////////////////客户来访费用/////////////////////////////////
////获得客户来访费用的 服务器分页	
	 var costData = {};
	 var visitId=jQuery('#visitId').val();
	 costData.visitId=visitId;
	 var costTable;
	    jQuery(document).ready(function () {
	    	costTable = jQuery('#costTable').DataTable({
	            "serverSide": true,
	            "iDisplayLength":5,
	            "ordering": false,
	            "ajax": {
	                "dataType": "json",
	                "type": "get",
	                "cache": false,
	                "url":window.rootPath+ '/ui/customerVisiting/getVisitCost',
	                "data": function (d) {
	                    return $.extend({}, d, costData);
	                }
	            },
	            columns: [
	                {
	                    data: null,
	                    defaultContent: ""//排序
	                },
	                {
	                    data: null,
	                    defaultContent: "",
	                    render: function (data, type, full, meta) {
	    	            	var id=data.id
	    	            	var operate ='<input type="checkbox" class="checkchild2">';
	    	            	return operate;
	    	            } 
	                },
	                {
	                    data: 'costName'
	                },
	                /*{
	                    data: 'price'
	                },*/
	                {
	                    data: 'amount'
	                },	             
	                {
	                    data: 'totalPrice'
	                }
	                ],
	            "drawCallback": function (oSettings) {
	                var k = 0;
	                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
	                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
	                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
	                    k++;
	                }
	            }
	        });
	    });
////编辑来访费用//////
	    jQuery('.editCostBtn').on('click',function(){
		       var selects=getSelect("#costTable",1);
		 	   if(selects.length>1){
		 		   $.springLemonDialog({
		 		         content: '只能编辑一条记录',// 确认文本
		 		         clickButton: function (sender, modal, index) {// 按钮事件处理
		 		             $(this).closeDialog(modal);
		 		         }
		 		   }); 
		 	   }
		 	   else if(selects.length==0){
		 		   $.springLemonDialog({
		 		         content: '请选择要编辑的记录',// 确认文本
		 		         clickButton: function (sender, modal, index) {// 按钮事件处理
		 		             $(this).closeDialog(modal);
		 		         }
		 		   }); 
		 	   }else if(selects.length==1){
			 		jQuery("#costId").val(selects[0].id);
		          	jQuery('#costcreatetime').val(selects[0].createTime);
		          	jQuery("#costName").val(selects[0].costName);
		    		//jQuery("#price").val(selects[0].price);
		    		jQuery('#amount').val(selects[0].amount);
		    		jQuery('#totalPrice').val(selects[0].totalPrice);
		    		jQuery('#visitingCostModal').modal('show');	
		 	   }	
		    })
		    ///////删除来访费用
		    jQuery('.deleteCostBtn').on('click', function () {
			   var selects=getSelect("#costTable",1);
			   var url=window.rootPath+"/ui/customerVisiting/delVisitCost";
			   delSelect(selects,url,costTable) 
			});
		    
		    ///////列表中的全选
		    $("#checkAll2").click(function(){
		    	var check = $(this).prop("checked");
		        $(".checkchild2").prop("checked", check);
			});	       
//////////////////保存来访费用//////////
		jQuery('.saveCostBtn').on('click',function(){
			if (jQuery("#visitingCostForm") && !jQuery("#visitingCostForm").Validform({
				tiptype : 3,
				showAllError : true
			}).check(false)) {
				return;
			};
			saveVisit(3);	
		})
	function saveVisitCost(visitId){
		var id=jQuery("#costId").val();
		var costcreatetime=jQuery("#costcreatetime").val();
		var costName=jQuery("#costName").val();
		//var price=jQuery("#price").val();
		var amount=jQuery('#amount').val();
		var totalPrice=jQuery('#totalPrice').val();
		var url=window.rootPath+"/ui/customerVisiting/saveVisitCost";
		var d;
		if(id==''){
	      	  d = {
	      			"costName": costName,
	   	            //"price": price,
	   	            "amount": amount,
	   	            "totalPrice": totalPrice,
	   	            "customerVisiting": {
	   	                "id": visitId
	   	            } 
	   	        };
	      	  	jQuery.ajax({
		          type: 'post',
		          url: encodeURI(url),
		          data: JSON.stringify(d),
		          dataType: 'json',
		          contentType: 'application/json;charset=utf-8',
		          success: function (data) {
		        		jQuery('#visitingCostModal').modal('hide');
		        		costData.visitId=visitId;
		        		jQuery('#visitId').val(visitId);
		        		costTable.draw();
		          }
	      	  	});
	      }else{
	      	d = {
	   	            "id":id,
	   	            "createTime":costcreatetime,
	   	            "costName": costName,
	   	            //"price": price,
	   	            "amount": amount,
	   	            "totalPrice": totalPrice,
	   	            "customerVisiting": {
	   	                "id": visitId
	   	            } 
	   	        };
	      	jQuery(".btn").attr("disabled", true);
	      	jQuery.ajax({
		          type: 'post',
		          url:  encodeURI(url),
		          data: JSON.stringify(d),
		          dataType: 'json',
		          contentType: 'application/json;charset=utf-8',
		          success: function (data) {
		        	jQuery(".btn").attr("disabled", false);
		          	jQuery('#visitingCostModal').modal('hide');
		          	jQuery('#visitId').val(visitId);
		          	costTable.draw(false);
		          }
		      });
	      }
	}
/////////新增来访费用////////////////////////////////////////////////////////////////
		jQuery(".addCostBtn").on("click",function(){
			var id=jQuery('#visitId').val();
			if (jQuery("#customerVisit") && !jQuery("#customerVisit").Validform({
				tiptype : 3,
				showAllError : true
			}).check(false)) {
				return;
			};
			jQuery("#costId").val('');
			jQuery("#costName").val('');
			//jQuery("#price").val('');
			jQuery('#amount').val('');
			jQuery('#totalPrice').val('');
			jQuery("#visitingCostModal").modal('show');	
	    });	

	
})